package com.qiyuesuo.oss.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiyuesuo.oss.entity.FileInfo;
import com.qiyuesuo.oss.mapper.FileMapper;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;


/**
 * @Author： xulinbo
 * @Description：
 * @Date： 18:22 2022/4/26
 **/
@Service
public class FileServiceImpl implements FileService {
    /**
     * Save the uploaded file to this folder
     */
    private static String FILE_PAHT = "D:\\IdeaSubject\\qiyuesuo-cloud\\oss\\src\\main\\resources\\file\\";

    @Autowired
    private FileMapper fileMapper;

    @Override
    public String saveUploadedFiles(MultipartFile file) throws IOException {

        if (file.isEmpty()) {
           return "上传文件有误";
        }
        FileInfo info = new FileInfo();
        String uuid = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        info.setId(uuid);
        info.setFileName(fileName);
        info.setFilePath(FILE_PAHT);
        fileMapper.insert(info);
        byte[] bytes = file.getBytes();
        Path path = Paths.get(FILE_PAHT + fileName);
        Files.write(path, bytes);
        return uuid;
    }

    @Override
    public FileInfo getFileInfo(String fileId) {
        FileInfo info = fileMapper.selectOne(new QueryWrapper<FileInfo>().eq("id", fileId));
        return info;
    }


}
